import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom'
import { connect } from 'dva';
import {
  Form, Input, DatePicker, Select, Button, Card, Upload, Radio, Modal, Tooltip,Icon,message,Row,Col
} from 'antd';
import {Map, Marker, NavigationControl,MapTypeControl,ScaleControl,OverviewMapControl, InfoWindow,TrafficLayer,Road} from 'react-bmap'  ;
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import UploadFile from '../../components/Upload/index';
import docCookies from "../../common/DocCookies";

const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;
const seekTypeNameValue = ["","寻人","寻物","车辆求助","寻找失主","其他求助"];
let map;
@connect(state => ({
  seekHelp: state.seekHelp,
}))
@Form.create()
export default class SeekAdd extends PureComponent {
  state = {
    id:-1,
    rsId:docCookies.getItem("rsId"),
    userId:docCookies.getItem("userId"),
    userName:docCookies.getItem("userName"),

    areaTitle:'走失位置',
    areaAddr:'乌鲁木齐市新市区新疆软件园发展有限公司',
    photoLabel:'人物近照',
    lng:87.490354,
    lat:43.853289,
    maxFileSize:3,
    fileList: [],
    photoInfo:[],

    showDetail:false,

    seekTypeValue:"1",

    iamgeVisible:false,
    imageSrc:""
  };

  ////初始化渲染后触发 整个过程只调用一次
  componentDidMount() {
    const { form , dispatch} = this.props;

    if(this.props.location.query) {
      var seekHelpId = this.props.location.query.seekHelpId;
      var showDetail = this.props.location.query.showDetail;
      if (seekHelpId) {
        if(showDetail){
          this.setState({
            showDetail:showDetail
          });
        }
        const params = {
          seekHelpId: seekHelpId
        };

        dispatch({
          type: 'seekHelp/fetchGetSeekHelpInfoById',  //请求的action
          payload: params,
          callback: (res) => {
            form.setFields({
              seekerName: {value: res.seekerName},
              seekTitle: {value: res.seekTitle},
              seekDes: {value: res.seekDes},
              contacts: {value: res.contacts},
              contactsTell: {value: res.contactsTell},
            })
            var areaAddr = res.areaAddr;
            var arr ;
            if(res.photoInfo ==""){
              arr = [] ;
            }else{
              arr = JSON.parse(res.photoInfo);
            }

            for(var i in arr){
              this.state.fileList.push({
                uid: (-99+i),
                name: 'default'+i+'.png',
                status: 'done',
                url: arr[i]
              })
            }

            this.setState({
              photoInfo: arr,
              fileList:this.state.fileList,
              lng:res.lng+0,
              lat:res.lat+0,
              areaAddr:res.areaAddr,
              id:res.id,
              rsId:res.rsId,
              seekTypeValue:res.seekType+"",
            });
            this.initBmap(res.lng,res.lat,false,areaAddr,this.state.showDetail == true ? true:false);
            this.handleRadioChange({target:{value:res.seekType}})
          }
        });
      }
    }else{
      this.initBmap(this.state.lng,this.state.lat,true,"乌鲁木齐市新市区新疆软件园发展有限公司",false);
    }
  }

  initBmap(lng,lat,autoPosition,areaAddrName,showDetail){
    var self = this;
    map = new BMap.Map("seekHelpAddress");

    function G(id) {
      return document.getElementById(id);
    }

    map.enableScrollWheelZoom(true);
    var point = new BMap.Point(lng,lat);
    map.centerAndZoom(point, 15);
    /*if(autoPosition){
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          var mk = new BMap.Marker(r.point);
          map.addOverlay(mk);
          map.panTo(r.point);
        }
        else {
          alert('failed'+this.getStatus());
        }
      },{enableHighAccuracy: true})
    }else{
      var mk = new BMap.Marker(point);
      map.addOverlay(mk);
      map.panTo(point);
    }*/

    var mk = new BMap.Marker(point);
    map.addOverlay(mk);
    map.panTo(point);

    if(showDetail != true){
      map.addEventListener("click", this.dragendStop);
    }

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
      {"input" : "suggestId"
        ,"location" : map
      }
    );
    ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
      var str = "";
      var _value = e.fromitem.value;
      var value = "";
      if (e.fromitem.index > -1) {
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
      }
      str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

      value = "";
      if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
      }
      str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
      G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
      var _value = e.item.value;
      myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
      G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
      setPlace();
    });

    function setPlace(){
      map.clearOverlays();    //清除地图上所有覆盖物
      function myFun(){
        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        self.setState({
          lat: pp.lat,
          lng: pp.lng
        });
        map.centerAndZoom(pp, 18);
        map.addOverlay(new BMap.Marker(pp));    //添加标注
      }
      var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: myFun
      });
      local.search(myValue);
    }



    if(areaAddrName != ""){
      document.getElementById("suggestId").value = areaAddrName;
    }
  }

  //地图拖动停止事件
  dragendStop = ({type, target, pixel, point}) => {
    this.setState({
      lat: point.lat,
      lng: point.lng
    });

    map.clearOverlays();
    var mk = new BMap.Marker(point);
    map.addOverlay(mk);
    map.panTo(point);

    var getData = new BMap.Geocoder();
    getData.getLocation(point, function(rs) {
      var adressInfo = rs.addressComponents;
      var surroundingPois = rs.surroundingPois;
      var adress= adressInfo.province + adressInfo.city + adressInfo.district + adressInfo.street + adressInfo.streetNumber;
      if(surroundingPois.length > 0){
        adress += surroundingPois[0].title;
      }
      document.getElementById("suggestId").value = adress;
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.userId = this.state.userId;
        values.rsId = this.state.rsId;
        values.userName = this.state.userName;
        values.photoInfo = JSON.stringify(this.state.photoInfo);
        if(this.state.id != -1) values.id = this.state.id;

        values.addrCoordinate='{"lng":'+this.state.lng+',"lat":'+this.state.lat+'}';

        values.addrStr= document.getElementById("suggestId").value ;
        var tel = values.contactsTell;

        if(!(/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(tel))){
          message.error("不是完整的11位手机号或者正确的手机号前七位");
          return false;
        }

       this.props.dispatch({
          type: 'seekHelp/fetchSubmitSeekHelp',
          payload: values,
          callback:(res) =>{
            message.success(res.msg);
            setTimeout(this.cancelBack(),200);
          }
        });
      }
    });
  }

  getImageSrc = (imgSrc) => {
    this.setState({
      photoInfo: imgSrc
    });
  }

  handleRadioChange = ( e ) => {
    var _pl = '', _al = '';
    switch (e.target.value){
      case '1':
        _pl = '走失位置';
        _al = '人物近照';
        break;
      case '2':
        _pl = '丢失位置';
        _al = '物品照片';
        break;
      case '3':
        _pl = '车辆位置';
        _al = '车辆照片';
        break;
      case '4':
        _pl = '拾到位置';
        _al = '物品照片';
        break;
      case '5':
        _pl = '位置';
        _al = '照片';
        break;
    }
    this.setState({
      areaTitle: _pl,
      photoLabel: _al
    });
  }


  cancelBack = () => {
    history.go(-1);
  }

  renderSeekTypeByShowDetail = (showDetail,seekTypeValue) => {
    var seekTypeNameValue = ["","寻人","寻物","车辆求助","寻找失主","其他求助"];
    if(showDetail == true){
        if(seekTypeValue == 1){
            return (
              <FormItem
                {...formItemLayout}
                label="类型"
              >
                {getFieldDecorator('seekType', {
                  initialValue: seekTypeValue,
                })(
                  <Radio.Group disabled={true}>
                    <Radio value={seekTypeValue}>{seekTypeNameValue[seekTypeValue]}</Radio>
                  </Radio.Group>
                )}
              </FormItem>
            );
        }
    }else {
      return(
        <FormItem
          {...formItemLayout}
          label="类型"
        >
          {getFieldDecorator('seekType', {
            initialValue: seekTypeValue,
          })(
            <Radio.Group onChange={this.handleRadioChange} disabled={showDetail}>
              <Radio value="1">寻人</Radio>
              <Radio value="2">寻物</Radio>
              <Radio value="3">车辆求助</Radio>
              <Radio value="4">寻找失主</Radio>
              <Radio value="5">其他求助</Radio>
            </Radio.Group>
          )}
        </FormItem>
      );
    }
  }


  handleImagePlay = (imageSrc) => {
    this.setState({
      imageSrc:imageSrc,
      iamgeVisible:true
    });
  }
  handleCancelImageModal= () => {
    this.setState({
      iamgeVisible:false
    });
  }

  render() {
    const { formLoading } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const {  fileList ,areaAddr,photoInfo,iamgeVisible,imageSrc,areaTitle,photoLabel,maxFileSize,showDetail,seekTypeValue} = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    /*const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86',
      })(
        <Select style={{ width: 70 }}>
          <Option value="86">+86</Option>
          <Option value="87">+87</Option>
        </Select>
      );*/

    return (
      <PageHeaderLayout >
        <Card bordered={false}>
          <Form
            onSubmit={this.handleSubmit}
            hideRequiredMark
            style={{ marginTop: 8 }}
          >
           {/* 求助类型  1 寻人 2 寻物  3 车辆求助  4 寻找失主    5 其他*/}
            {
              showDetail == true ? (
                <FormItem
                  {...formItemLayout}
                  label="类型"
                >
                  {seekTypeNameValue[seekTypeValue]}
                </FormItem>
              ):(
              <FormItem
                {...formItemLayout}
                  label="类型"
                  >
                {getFieldDecorator('seekType', {
                  initialValue: seekTypeValue,
                })(
                  <Radio.Group onChange={this.handleRadioChange} disabled={showDetail}>
                  <Radio value="1">寻人</Radio>
                  <Radio value="2">寻物</Radio>
                  <Radio value="3">车辆求助</Radio>
                  <Radio value="4">寻找失主</Radio>
                  <Radio value="5">其他求助</Radio>
                  </Radio.Group>
                  )}
              </FormItem>
              )
            }
            <FormItem
              {...formItemLayout}
              label="求助人"
            >
              {getFieldDecorator('seekerName', {
                rules: [{
                  required: true, message: '请输入求助人',
                }],
              })(
                <Input placeholder="请输入求助人"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="标题"
            >
              {getFieldDecorator('seekTitle', {
                rules: [{
                  required: true, message: '请输入求助人',
                }],
              })(
                <Input placeholder="请输入求助人"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="描述"
            >
              {getFieldDecorator('seekDes', {
                rules: [{
                  required: true, message: '请输入请求描述',
                }],
              })(
                <TextArea style={{ minHeight: 32 }} placeholder="走失时间、走失地点、人物状况、外貌特征" rows={4}  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="联系人"
            >
              {getFieldDecorator('contacts', {
                rules: [{
                  required: true, message: '请输入联系人',
                }],
              })(
                <Input placeholder="请输入联系人"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="联系电话"
            >
              {getFieldDecorator('contactsTell', {
                rules: [{
                  required: true, message: '请输入电话',
                }],
              })(
                <Input placeholder="请输入电话"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label='搜地点'
              style={{marginBottom:2}}
            >
              <div id="r-result"><Input placeholder="搜地点" id="suggestId" name="suggestId" disabled={showDetail} /></div>
              <div id="searchResultPanel" style={{border:'1px solid #C0C0C0',width:'100%',height:'auto', display:'none'}}></div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={areaTitle}
              style={{marginBottom:2}}
            >
              <div id="seekHelpAddress" style={{width:'100%',height:400}}></div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={photoLabel}
            >
              {
                !showDetail?<UploadFile
                    maxFileCount = {maxFileSize}
                    defaultList={fileList}
                    getImgSrc={(imgSrc)=> this.getImageSrc(imgSrc)}
                    buttonName = "照片上传"
                    acceptName = 'image/*'
                    suffixDefault = {['jpg']}
                    data={{
                      userId:1,
                      filePath:'test/photo/'}}
                  />:
                  <div style={{marginLeft:5}}>
                    {
                      showDetail&&photoInfo[0]?<div style={{marginLeft:12,float:"left"}}>
                        <img src={photoInfo[0]} style={{width:60,height:60,marginLeft:0,cursor:"pointer" }}
                             onClick={() => this.handleImagePlay(photoInfo[0]) }/>
                      </div>:null
                    }
                    {
                      showDetail&&photoInfo[1]?<div style={{marginLeft:12,float:"left"}}>
                        <img src={photoInfo[1]} style={{width:60,height:60,marginLeft:0,cursor:"pointer" }}
                             onClick={() => this.handleImagePlay(photoInfo[1]) }/>
                      </div>:null
                    }
                    {
                      showDetail&&photoInfo[2]?<div style={{marginLeft:12,float:"left"}}>
                        <img src={photoInfo[2]} style={{width:60,height:60,marginLeft:0,cursor:"pointer" }}
                             onClick={() => this.handleImagePlay(photoInfo[2]) }/>
                      </div>:null
                    }
                  </div>

              }

            </FormItem>
            {
              showDetail == true ? (
                <FormItem {...submitFormLayout} style={{ marginTop: 32 }}  help="导播提交后，信息将推送到主持人界面，只有主持人播报并一键推送后才会在APP中显示" >
                  <Button style={{ marginLeft: 8 }} onClick={() => this.cancelBack()}>返回</Button>
                </FormItem>
              ) : (
                <FormItem {...submitFormLayout} style={{ marginTop: 32 }}  help="导播提交后，信息将推送到主持人界面，只有主持人播报并一键推送后才会在APP中显示" >

                  <Button type="primary" htmlType="submit" loading={formLoading}  disabled={showDetail} >
                    提交求助信息
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={() => this.cancelBack()}>取消</Button>
                </FormItem>
              )
            }

          </Form>
        </Card>
        <Modal
          visible={iamgeVisible}
          footer={null}
          onCancel={this.handleCancelImageModal}>
          <img alt="example" style={{ width: '100%' }} src={imageSrc} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
